/*
 * @Author: zll
 * @Date: 2024-05-11 12:19:52
 * @LastEditors: zll
 * @LastEditTime: 2024-05-22 17:39:23
 * @Description: file content
 * @FilePath: \erp-app\src\stores\menu.ts
 */
import { queryBadge, queryMenuList } from '@/service/sys';
import { defineStore } from 'pinia';

interface IMenu {
  id: string;
  name: string;
  meta: {
    icon: string;
    [key: string]: string;
  };
  path: string;
  badgeNum: number;
  children: IMenu[];
}
export const useMenu = defineStore({
  id: 'menuStore',
  state: (): { menuList: IMenu[] } => ({
    menuList: [],
  }),
  actions: {
    async getMenuList() {
      try {
        const res = await queryMenuList().finally(() => {
          uni.stopPullDownRefresh();
        });
        if (!res.data) {
          return;
        }
        this.menuList = res.data.map((item) => {
          return {
            name: item.name,
            path: item.path,
            meta: item.meta,
            children: item.children,
            badgeNum: 0,
          };
        });
        this.getBadeg();
        return res.data;
      } catch (error) {
        uni.showToast({
          title: error.message || error.msg,
          icon: 'none',
        });
      }
    },
    async getBadeg() {
      try {
        const res = await queryBadge();
        if (res.code === 0) {
          this.setBadge(res.data);
        }
      } catch (error) {
        uni.showToast({
          title: error.message || error.msg,
          icon: 'none',
        });
      }
    },
    setBadge(badegMap: { [key: string]: number }) {
      if (this.menuList.length) {
        const handle = function (_list) {
          _list.forEach((menu) => {
            menu.badgeNum = badegMap[menu.path] || 0;
            if (menu.children?.length) {
              handle(menu.children);
            }
          });
        };
        handle(this.menuList);
      }
    },
  },
});
